package com.yiren.dbaa.module.practice_set.basestation.view.activity;

import static com.yiren.dbaa.util.ZipUtils.TAG;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qxwz.sdk.configs.AccountInfo;
import com.qxwz.sdk.configs.SDKConfig;
import com.qxwz.sdk.core.CapInfo;
import com.qxwz.sdk.core.IRtcmSDKCallback;
import com.qxwz.sdk.core.RtcmSDKManager;
import com.qxwz.sdk.types.KeyType;
import com.yiren.backstage.communication.api.impl.BluetoothCommunicationApiImpl;
import com.yiren.backstage.communication.thread.RTKConnection;
import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.dbaa.R;
import com.yiren.dbaa.activity.BaseActivity;
import com.yiren.dbaa.module.practice_set.basestation.bean.BaseStationBean;
import com.yiren.dbaa.module.practice_set.basestation.contract.CalibrationContract;
import com.yiren.dbaa.module.practice_set.basestation.presenter.CalibrationPresenter;
import com.yiren.dbaa.module.practice_set.basestation.view.dialog.CalibrationDialog;
import com.yiren.dbaa.util.DecimalTransferUtil;
import com.yiren.dbaa.util.DistanceUtil;
import com.yiren.dbaa.view.toast.MessageBox;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lwb
 * @date : 2022/12/13 17:21
 * @description:基站标定
 */
public class CalibrationActivity extends BaseActivity implements IRtcmSDKCallback, CalibrationContract.CalibrationView {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.ll_calibration_tip)
    LinearLayout llCalibrationTip;
    @BindView(R.id.ll_calibration_info)
    LinearLayout llCalibrationInfo;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_longitude)
    TextView tvLongitude;
    @BindView(R.id.tv_latitude)
    TextView tvLatitude;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.et_state_info)
    EditText etStateInfo;
    @BindView(R.id.tv_calibration)
    TextView tvCalibration;

    private Intent intent;
    private BaseStationBean baseStationBean;
    private CalibrationContract.Presenter calibrationPresenter;
    private boolean isStart = false;

    private static final String AK = "A4902m5pqodn";
    private static final String AS = "0e8288edb9242788";
    private static final String DEVICE_ID = "DJ00000002";
    private static final String DEVICE_TYPE = "RTK";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calibration);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        tvTitle.setText("基站标定");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("标定说明");
        intent = getIntent();
        baseStationBean = (BaseStationBean) intent.getSerializableExtra("baseStation");
        calibrationPresenter = new CalibrationPresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        authQianXun();
    }

    /**
     * 验证千寻
     */
    public void authQianXun() {
        SDKConfig.Builder builder = SDKConfig.builder()
                .setAccountInfo(AccountInfo.builder()
                        .setKeyType(KeyType.QXWZ_SDK_KEY_TYPE_AK)
                        .setKey(AK)
                        .setSecret(AS)
                        .setDeviceId(DEVICE_ID)
                        .setDeviceType(DEVICE_TYPE)
                        .build())
                .setRtcmSDKCallback(this);
        RtcmSDKManager.getInstance().init(builder.build());
        RtcmSDKManager.getInstance().auth();
    }

    @Override
    public void onData(int i, byte[] bytes) {
        byte[] data = new byte[1024];
        //将数组转成1024个字节发送，避免数据串行
        System.arraycopy(bytes, 0, data, 0, bytes.length);
//        MessageBox.show(this, "rtcm data received, data length is " + bytes.length);
//        Log.d(TAG, "rtcm data received, data length is " + bytes.length);
        BluetoothCommunicationApiImpl.getInstance(this).writeData(data, "", null);
    }

    @Override
    public void onStatus(int status) {
//        MessageBox.show(this, "status changed to " + status);
        Log.d(TAG, "status changed to " + status);
    }

    @Override
    public void onAuth(int code, List<CapInfo> caps) {
        if (code == com.qxwz.sdk.core.Constants.QXWZ_SDK_STAT_AUTH_SUCC) {
//            MessageBox.show(this, "auth successfully.");
            System.out.println("aaaaaaaaaaaaa:" + "auth successfully.");
            Log.d(TAG, "auth successfully.");
            for (CapInfo capInfo : caps) {
                Log.d(TAG, "capInfo:" + capInfo.toString());
            }
            /* if you want to call the start api in the callback function, you must invoke it in a new thread. */
            new Thread() {
                public void run() {
                    RtcmSDKManager.getInstance().start(com.qxwz.sdk.core.Constants.QXWZ_SDK_CAP_ID_NOSR);
                }
            }.start();
        } else {
            System.out.println("aaaaaaaaaaaaa:" + "failed to auth, code is " + code);
//            MessageBox.show(this, "failed to auth, code is " + code);
            Log.d(TAG, "failed to auth, code is " + code);
            runOnUiThread(() -> MessageBox.show(this, "failed to auth, code is " + code));
        }
    }

    @Override
    public void onStart(int code, int i1) {
        if (code == com.qxwz.sdk.core.Constants.QXWZ_SDK_STAT_CAP_START_SUCC) {
            System.out.println("aaaaaaaaaaaaa:" + "start successfully.");
//            MessageBox.show(this, "start successfully.");
            Log.d(TAG, "start successfully.");
            isStart = true;
            new Thread() {
                public void run() {
                    while (isStart) {
                        RtcmSDKManager.getInstance().sendGga(SignalGConstant.gpsGpgga);
//                        RtcmSDKManager.getInstance().sendGga(GGA);
                        SystemClock.sleep(1000);
                    }
                }
            }.start();
        } else {
            System.out.println("aaaaaaaaaaaaa:" + "failed to start, code is " + code);
//            MessageBox.show(this, "failed to start, code is " + code);
            Log.d(TAG, "failed to start, code is " + code);
            runOnUiThread(() -> MessageBox.show(this, "failed to start, code is " + code));
        }
    }

    @OnClick({R.id.iv_back, R.id.tv_right, R.id.tv_calibration})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:  //返回
                finish();
                break;
            case R.id.tv_right: //标定说明
                CalibrationDialog.showCalibrationDialog(this);
                break;
            case R.id.tv_calibration: //标定
                llCalibrationTip.setVisibility(View.GONE);
                llCalibrationInfo.setVisibility(View.VISIBLE);
                calibrationPresenter.calibrationBaseStation(baseStationBean, this);
                break;
        }
    }

    @Override
    public void setBaseId(String baseId) {
        tvId.setText(baseId);
    }

    @Override
    public void setPositionStatus(float satelliteNum) {
        tvStatus.setText(satelliteNum + "");
    }

    @Override
    public void setBaseLocation(String longitude, String latitude, String altitude) {
        tvLongitude.setText(longitude);
        tvLatitude.setText(latitude);
    }

    @Override
    public void setBaseLocation(String longitude, String latitude, String altitude, String address, String distance) {
        tvLongitude.setText(longitude);
        tvLatitude.setText(latitude);
        tvLocation.setText(address);
        tvDistance.setText(distance + "KM");
    }

    @Override
    public void setCalibrationEdit() {
        etStateInfo.append(SignalGConstant.allData + "\n");
        if (etStateInfo.getText().length() > 1500) {
            etStateInfo.setText("");
        }
    }

    @Override
    public void setCalibrationSuccess() {
        tvCalibration.setText("已完成标定");
    }

    @Override
    protected void onPause() {
        super.onPause();
        isStart = false;
        RtcmSDKManager.getInstance().stop(com.qxwz.sdk.core.Constants.QXWZ_SDK_CAP_ID_NOSR);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RTKConnection.useCommand = false;
        RtcmSDKManager.getInstance().cleanup();
        calibrationPresenter.removeThread();
    }

}